package com.readygo.boot_test.auth;

import com.readygo.boot_test.entity.auth.Role;
import com.readygo.boot_test.entity.auth.SecurityUser;
import com.readygo.boot_test.repository.auth.RoleRepository;
import com.readygo.boot_test.repository.auth.SecurityUserRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.thymeleaf.util.StringUtils;

import java.util.List;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    private SecurityUserRepository securityUserRepository;
    private RoleRepository roleRepository;

    public UserDetailsServiceImpl(SecurityUserRepository securityUserRepository, RoleRepository roleRepository) {
        this.securityUserRepository = securityUserRepository;
        this.roleRepository = roleRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //获取用户信息
        if (StringUtils.isEmpty(username)) {
            throw new UsernameNotFoundException("username empty");
        }

        SecurityUser user = securityUserRepository.findFirstByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("not found");
        }
        List<Role> roles = roleRepository.findAllByRoleKey_SecurityUserId(user.getSecurityUserId());

        UserDetailsModel userDetails = new UserDetailsModel();
        BeanUtils.copyProperties(user, userDetails);
        userDetails.setAuthorities(roles);

        return userDetails;
    }
}
